#include "ClientHandlerTask.h"
#include "Socket.h"
#include "HTTPHandler.h"
#include "HTTPRequest.h"
SK

ClientHandlerTask::ClientHandlerTask (JarvCore *core, Socket *soc)
: soc(soc), handler (new HTTPHandler(core)), core(core)
{
	buffer = new byte [4096];
}

ClientHandlerTask::~ClientHandlerTask()
{
	if (soc)
		delete soc;

	if (handler)
		delete handler;

	delete [] buffer;
}


void ClientHandlerTask::run (void)
{
	//send and recieve data from cleints for processing here
	int ret=1;

	while (ret > 0)
	{
		
        ret = soc->recv (buffer, 4096);

		if (ret < 1)
			break;

		request += String ((char *)buffer, ret);

		int loc=0;

		while (loc != String::npos)
		{
			loc = request.find ("\r\n\r\n");

			if (loc != String::npos)
			{
				String sub = request.substr (0, loc);
				HTTPRequest req = HTTPRequest (sub);
				String postData;

				int postEnd = loc + 4;
				if (req.method == HTTP_POST)
				{
					if (req.contentLength > 0)
					{
						postData = request.substr(sub.length()+4, req.contentLength);
						postEnd = loc + 4 + req.contentLength;
					}
				}


				handler->processRequest (sub, soc, req, postData);

				if (!req.conKeepAlive)
					soc->close();
				

				request = request.substr (postEnd);
			}
		}
	}

	soc->close();
}

EK